package tv.accedo.achi.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import tv.accedo.achi.dao.UserDao;
import tv.accedo.achi.model.User;

@Component
public class UserService {
	private User user; 
	private UserDao userDao;
	
	/**
	 * fetch one specific user's score value
	 * @param username User Name
	 * @return User Score
	 */
	public long getScoreByUsername(String username) {
		long score = -1; 
		user = userDao.getUserByUsername(username); 
		if (user != null) score = user.getScore(); 
		return score; 
	}
	
	/**
	 * Get all users score, return in the format of Json
	 * @return all users score in Json
	 */
	public String getAllJsonUsersScore() {
		String jsonUsers = "]}"; 
		List<User> userList = new ArrayList<User>(); 
		userList = userDao.getAllUsers(); 
		for(Iterator<User> iter = userList.iterator(); iter.hasNext(); ) {
			user = iter.next(); 
			jsonUsers = "{username:'" + user.getUsername() + "', score:'" + user.getScore() + "'}," + jsonUsers;
		}
		jsonUsers = "{users:[" + jsonUsers;
		
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jsonUsers; 
	}
	
	
	public User getUser() {
		return user;
	}

	@Resource
	public void setUser(User user) {
		this.user = user;
	}

	public UserDao getUserDao() {
		return userDao;
	}

	@Resource
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
}
